package com.bluesky.service.lesson032.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bluesky.dto.lesson032.CreateOrderRequest;
import com.bluesky.mapper.lesson032.Lesson032OrderMapper;
import com.bluesky.mq.sender.IMsgSender;
import com.bluesky.po.lesson032.Lesson032OrderPO;
import com.bluesky.service.lesson032.ILesson032OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class Lesson032OrderServiceImpl extends ServiceImpl<Lesson032OrderMapper, Lesson032OrderPO> implements ILesson032OrderService {

    @Autowired
    private IMsgSender msgSender;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String createOrder(CreateOrderRequest req) {
        Lesson032OrderPO orderPO = new Lesson032OrderPO();
        orderPO.setId(IdUtil.fastSimpleUUID());
        orderPO.setGoods(req.getGoods());
        orderPO.setPrice(req.getPrice());
        this.save(orderPO);

        log.info("订单创建成功，订单号：{},投递订单消息", orderPO.getId());

        if (req.getDelaySeconds() == 0){
            //投递订单消息（立即投递）
            this.msgSender.send(orderPO);
        }else{
            //投递订单消息（延迟投递）
            this.msgSender.send(req.getDelaySeconds(), TimeUnit.SECONDS, orderPO);
        }
        return orderPO.getId();
    }

}
